<template>
  <!-- 电量统计记录表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="15%"
    draggable
    @close="closeDialog"
  >
    <el-descriptions
      class="margin-top"
      title=""
      :column="1"
      size="large"
      v-show="props.isReadonly"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">年月</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.statisticalYearMonth }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">类型</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{
            dictionaryStore.filterDictName(
              "ElectricType",
              formData.electricStatisticalType
            )
          }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">电量</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.electricQuantity }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="年月"
            prop="statisticalYearMonth"
            label-width="50px"
          >
            <el-date-picker
              v-model="formData.statisticalYearMonth"
              style="width: 100%"
              type="month"
              placeholder="请选择年月"
              value-format="YYYY-MM"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="类型"
            prop="electricStatisticalType"
            label-width="50px"
          >
            <el-select
              style="width: 100%"
              v-model="formData.electricStatisticalType"
              placeholder="请选择类型"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'ElectricType'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="电量" prop="electricQuantity" label-width="50px">
            <el-input
              v-model="formData.electricQuantity"
              placeholder="请输入电量"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESELECTRICSTATISTICALRECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  statisticalYearMonth: [
    { required: true, message: "请输入年月", trigger: "change"}
  ],
  electricStatisticalType: [{ required: true, message: "请选择类型", trigger: "blur"}],
  electricQuantity: [
    { required: true, message: "请输入电量", trigger: "blur" },
    { pattern: /^\d{1,18}(\.\d{0,6})?$/, message: "请输入数字" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  statisticalYearMonth: "",
  electricStatisticalType: "",
  electricQuantity: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        statisticalYearMonth,
        electricStatisticalType,
        electricQuantity,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        statisticalYearMonth,
        electricStatisticalType,
        electricQuantity,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      formData.electricStatisticalType = String(newVal.electricStatisticalType)
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.statisticalYearMonth = "";
  formData.electricStatisticalType = "";
  formData.electricQuantity = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 电量统计记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/meselectricstatisticalrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
